package com.niji.littly_donkey_android.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.makeramen.roundedimageview.RoundedImageView;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.MyHomeVideoAdapter;
import com.niji.littly_donkey_android.adapter.MyHomeVideoLikeAdapter;
import com.niji.littly_donkey_android.bean.Video;
import com.niji.littly_donkey_android.common.MultipartRequest;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import com.niji.littly_donkey_android.view.CircleImageView;
import org.json.JSONObject;

import java.io.File;
import java.util.*;

public class MyHomePageActivity extends AppCompatActivity {

    private static final String TAG  = "MyHomePageActivity";

    private Button my_home_page_return;

    private Button my_home_page_update_info;

    private Button my_home_shooting;

    private RecyclerView my_home_page_flow;

    private RecyclerView my_home_page_like_flow;

    private ImageView my_home_page_background;

    private CircleImageView my_home_page_avatar;

    private TextView my_home_page_nickname;

    private TextView my_home_page_signature;

    private TextView my_home_page_sage;

    private TextView my_home_page_city;

    private RelativeLayout my_home_page_loading;

    private Button my_home_page_update_background;


    /**
     * 图片相关
     */
    private static String photoPath = null;
    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private static final int CHOOSE_PHOTO = 2;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_home_page_activity);
        init();
        myHomePageReturn();
        myHomePageUpdateInfo();
        myHomeShooting();
        changeVideoAndLike();
        updateBackground();
    }

    private void updateBackground() {
        my_home_page_update_background = findViewById(R.id.my_home_page_update_background);

    }

    /***
     * 作品和喜欢切换
     */
    private void changeVideoAndLike() {
        my_home_page_loading = findViewById(R.id.my_home_page_loading);
        TextView my_home_video = findViewById(R.id.my_home_video_change);
        TextView my_home_like = findViewById(R.id.my_home_like);
        ImageView my_home_like_img = findViewById(R.id.my_home_like_img);
        ImageView my_home_video_img = findViewById(R.id.my_home_video_img);
        my_home_page_flow = findViewById(R.id.my_home_page_flow);
        my_home_page_like_flow = findViewById(R.id.my_home_page_like_flow);
        my_home_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                my_home_video.setTextColor(Color.parseColor("#333333"));
                my_home_like.setTextColor(Color.parseColor("#999999"));
                my_home_like_img.setVisibility(View.INVISIBLE);
                my_home_video_img.setVisibility(View.VISIBLE);
                my_home_page_like_flow.setVisibility(View.INVISIBLE);
                my_home_page_flow.setVisibility(View.VISIBLE);
                my_home_shooting.setVisibility(View.VISIBLE);
                my_home_page_loading.setVisibility(View.VISIBLE);
                showVideos();
            }
        });

        my_home_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                my_home_video.setTextColor(Color.parseColor("#999999"));
                my_home_like.setTextColor(Color.parseColor("#333333"));
                my_home_like_img.setVisibility(View.VISIBLE);
                my_home_video_img.setVisibility(View.INVISIBLE);
                my_home_page_like_flow.setVisibility(View.VISIBLE);
                my_home_page_flow.setVisibility(View.INVISIBLE);
                my_home_shooting.setVisibility(View.INVISIBLE);
                my_home_page_loading.setVisibility(View.VISIBLE);
                showLikeVideos();
            }
        });

    }

    /**
     * 我的作品
     */
    private void showVideos() {
        my_home_page_loading = findViewById(R.id.my_home_page_loading);
        ArrayList<Video> videos = new ArrayList<>();
        String url = UrlUtil.URL + "/user/videos/list?page=1&per_page=50";
        RequestQueue requestQueue= Volley.newRequestQueue(MyHomePageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map  = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0){
                        Map<String,Object> dataMap = (Map) map.get("data");
                        Log.i(TAG,dataMap.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) dataMap.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Integer id = (Integer) mapList.get(i).get("id");
                            Integer user_id = (Integer) mapList.get(i).get("user_id");
                            Integer attractions_id = (Integer) mapList.get(i).get("attractions_id");
                            String title = (String) mapList.get(i).get("title");
                            String url1 = (String) mapList.get(i).get("url");
                            String cover = (String) mapList.get(i).get("cover");
                            Integer likes = (Integer) mapList.get(i).get("likes");
                            Integer comments = (Integer) mapList.get(i).get("comments");
                            Integer commission = (Integer) mapList.get(i).get("commission");
                            String remark = (String) mapList.get(i).get("remark");
                            Video video = new Video();
                            video.setId(id);
                            video.setVideoUrl(url1);
                            video.setLikes(likes);
                            video.setAttractionsId(attractions_id);
                            video.setComments(comments);
                            video.setCommission(commission);
                            video.setTitle(title);
                            video.setUrl(UrlUtil.URL + cover);
                            video.setUserId(user_id);
                            videos.add(video);
                        }
                        my_home_page_flow.setHasFixedSize(true);
                        my_home_page_flow.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
                        my_home_page_flow.setAdapter(new MyHomeVideoAdapter(MyHomePageActivity.this,videos));
                        my_home_page_loading.setVisibility(View.INVISIBLE);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("错误", volleyError.toString());
                Toast.makeText(MyHomePageActivity.this, "网络失败", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(MyHomePageActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);


    }

    /**
     * 喜欢的作品列表
     */
    private void showLikeVideos() {
        my_home_page_loading = findViewById(R.id.my_home_page_loading);
        ArrayList<Video> videos = new ArrayList<>();
        String url = UrlUtil.URL + "/user/give/likes/list?page=1&per_page=50";
        RequestQueue requestQueue= Volley.newRequestQueue(MyHomePageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map  = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0){
                        Map<String,Object> dataMap = (Map) map.get("data");
                        Log.i(TAG,dataMap.toString());
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) dataMap.get("data");
                        Log.i(TAG,mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            List<Map<String, Object>> videosInfo = (List<Map<String, Object>>) mapList.get(i).get("videos_info");
                            Log.i(TAG,videosInfo.toString());
                            for (int j = 0; j < videosInfo.size(); j++) {
                                Integer id = (Integer) videosInfo.get(j).get("id");
                                Integer user_id = (Integer) videosInfo.get(j).get("user_id");
                                Integer attractions_id = (Integer) videosInfo.get(j).get("attractions_id");
                                String title = (String) videosInfo.get(j).get("title");
                                String url1 = (String) videosInfo.get(j).get("url");
                                String cover = (String) videosInfo.get(j).get("cover");
                                Integer likes = (Integer) videosInfo.get(j).get("likes");
                                Integer comments = (Integer) videosInfo.get(j).get("comments");
                                Integer commission = (Integer) videosInfo.get(j).get("commission");
                                String remark = (String) videosInfo.get(j).get("remark");
                                Video video = new Video();
                                video.setId(id);
                                video.setLikes(likes);
                                video.setAttractionsId(attractions_id);
                                video.setComments(comments);
                                video.setCommission(commission);
                                video.setTitle(title);
                                video.setUrl(UrlUtil.URL + cover);
                                video.setUserId(user_id);
                                videos.add(video);
                            }

                        }
                        my_home_page_like_flow.setHasFixedSize(true);
                        my_home_page_like_flow.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
                        my_home_page_like_flow.setAdapter(new MyHomeVideoLikeAdapter(MyHomePageActivity.this,videos));
                        my_home_page_loading.setVisibility(View.INVISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("错误", volleyError.toString());
                Toast.makeText(MyHomePageActivity.this, "网络失败", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(MyHomePageActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);


    }


    @Override
    protected void onStart() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //不加这个clearFlags好像就没效果
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            //设置导航栏透明(就是虚拟键那一栏)

            //设置状态栏(或者叫通知栏)透明
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        super.onStart();
    }

    /**
    *初始化信息
     */
    private void initInfo(){
        String url = UrlUtil.URL + "/user/user/info";
        RequestQueue requestQueue= Volley.newRequestQueue(MyHomePageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map  = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0){
                        Map<String,Object> dataMap = (Map) map.get("data");
                        String nickname = (String) dataMap.get("nickname");
                        Integer sex = (Integer) dataMap.get("sex");
                        Integer age = (Integer) dataMap.get("age");
                        String avatar = (String) dataMap.get("avatar");
                        String city = (String) dataMap.get("city");
                        String signature = (String) dataMap.get("signature");
                        String background = (String) dataMap.get("background");
                        NetworkGlideImageLoader.getInstance().displayImage((Activity) MyHomePageActivity.this,UrlUtil.URL + avatar,my_home_page_avatar,0,0);
                        NetworkGlideImageLoader.getInstance().displayImage((Activity) MyHomePageActivity.this,UrlUtil.URL + background,my_home_page_background,0,0);
                        my_home_page_nickname.setText(nickname);
                        my_home_page_signature.setText(signature);
                        my_home_page_city.setText(city);
                        if (sex == 1){
                            my_home_page_sage.setText("男-" + age + "岁");
                        }else if(sex == 2){
                            my_home_page_sage.setText("女-" + age + "岁");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("错误", volleyError.toString());
                Toast.makeText(MyHomePageActivity.this, "网络失败", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(MyHomePageActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);
    }

    private void init() {
        my_home_page_background = findViewById(R.id.my_home_page_background);
        my_home_page_avatar = findViewById(R.id.my_home_page_avatar);
        my_home_page_nickname = findViewById(R.id.my_home_page_nickname);
        my_home_page_signature = findViewById(R.id.my_home_page_signature);
        my_home_page_sage = findViewById(R.id.my_home_page_sage);
        my_home_page_city = findViewById(R.id.my_home_page_city);
        initInfo();
        showVideos();

    }


    /**
     * 拍摄
     */
    private void myHomeShooting() {
        my_home_shooting = findViewById(R.id.my_home_shooting);
        my_home_shooting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyHomePageActivity.this, ShootingReleaseActivity.class));
                   
            }
        });
    }

    /**
     * 修改资料
     */
    private void myHomePageUpdateInfo() {
        my_home_page_update_info = findViewById(R.id.my_home_page_update_info);
        my_home_page_update_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyHomePageActivity.this, UpdateInfoActivity.class));
                   
            }
        });
    }

    /**
     * 保存背景图片
     */
    private void savaBackground(){
        File fs = null;
        if (photoPath != null) {
            fs = new File(photoPath);
        }
        String url = UrlUtil.URL + "/user/modify/info";
        if (fs != null) {
            RequestQueue mSingleQueue = Volley.newRequestQueue(MyHomePageActivity.this);
            MultipartRequest multipartRequest = new MultipartRequest(
                    url, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Map<String, Object> map = JsonUtil.jsonToMap(response.toString());
                        Integer code = (Integer) map.get("code");
                        if (code == 0) {
                            String data = (String) map.get("data");
                            Toast.makeText(MyHomePageActivity.this, data, Toast.LENGTH_LONG).show();
                            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            finish();
                        } else if (code == -1) {
                            Toast.makeText(MyHomePageActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(MyHomePageActivity.this, GetPhoneCodeActivity.class);
                            intent.putExtra("loginCode", "-1");
                            startActivity(intent);
                            finish();
                        } else {
                            String data = (String) map.get("message");
                            Toast.makeText(MyHomePageActivity.this, data, Toast.LENGTH_SHORT).show();
                            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                            finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError e) {
                    Log.e(TAG, e.getMessage(), e);
                    try {
                        byte[] htmlBodyBytes = e.networkResponse.data;
                        Log.e(TAG, new String(htmlBodyBytes), e);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }, "background", fs) {
            };
            multipartRequest.setSendCookie(new ConnectViaSession(MyHomePageActivity.this).GetSession());
            multipartRequest.setTag(TAG);
            mSingleQueue.add(multipartRequest);
        } else {
            overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
            finish();
        }
    }

    /**
     * 返回
     */
    private void myHomePageReturn() {
        my_home_page_return = findViewById(R.id.my_home_page_return);
        my_home_page_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savaBackground();
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();
            }
        });

    }
    /**
     * 重写返回按键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            savaBackground();
        }
        return true;
    }


    /**
     * 选择图片
     */
    /**
     * 请求读写SDK权限
     */
    public void choosePhoto(View view) {
        if (ContextCompat.checkSelfPermission(MyHomePageActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MyHomePageActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {
            openAlbum();
        }
    }

    /**
     * 打开图片浏览器
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "拒绝读取SD卡权限将无法获取照片", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        handleImageAfterKitKat(data);
                    } else {
                        handleImage(data);
                    }
                }
                break;
        }
    }

    /**
     * API19之后处理内容
     *
     * @param data onActivityResult 返回结果
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageAfterKitKat(Intent data) {
        /*ParcelFileDescriptor parcelFileDescriptor =
                null;
        try {
            parcelFileDescriptor = getContentResolver().openFileDescriptor(data.getData(), "r");
            Log.i(TAG, "handleImageAfterKitKat: " + parcelFileDescriptor.toString());
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            result.setImageBitmap(image);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        String imagePath = null;
        Uri uri = data.getData();
        Log.i(TAG, uri.toString());
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，通过documentId处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];    // 解析出数字格式id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                photoPath = imagePath;
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
                photoPath = imagePath;
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
            photoPath = imagePath;
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
            photoPath = imagePath;
        }
        displayImage(imagePath);
    }

    /**
     * 处理返回结果
     *
     * @param data onActivityResult 返回结果
     */
    private void handleImage(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /**
     * 根据图片路径，显示图片
     */
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            Bitmap bitmap1 = CirclePhotoUtil.centerSquareScaleBitmap(bitmap, 100);
            Drawable drawable = new BitmapDrawable(bitmap1);
            my_home_page_background.setImageDrawable(drawable);
        } else {
            Toast.makeText(this, "照片路径为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 使用ContentProvider获取图片路径
     *
     * @param uri       图片uri
     * @param selection 条件
     * @return 图片路径
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
}
